#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:煜
@file: DataOutPut.py
@time: 2018/10/25
"""
import sqlite3
import datetime
class DataOutPut(object):

    def __init__(self):
        self.__connection=sqlite3.connect("db.sqlite3")
        self.data=None

    def store_data(self,data):
        if data is None:
            None
        self.data=data

    def outPut(self):
        pass


    #存储书籍信息
    def saveBook(self):
        isPublic = 1
        createTime = datetime.datetime.now()
        bookfrom = "下书网"
        star = 0.0
        starCount = 0
        fontCount = 0

        isEnd = 1
        if int(self.data['totalRemarkPeople'])<1000:
            star=3.0
        elif int(self.data['totalRemarkPeople'])>1000 or int(self.data['totalRemarkPeople'])<2000:
            star=4.0
        elif int(self.data['totalRemarkPeople'])>2000:
            star=5.0

        if self.downloadImage(self.data['image'],self.data['id']):
            image=self.data['id']+'.jpg'
        else:
            image='/Book/Images/default.jpg'
        print(self.data['bookName'])

        cursor = self.__connection.cursor()
        sql = "insert OR IGNORE into easyRead_book(id,title,author,image,desc,isPublic,createTime,bookfrom,star,starCount,fontCount,totalChapter,remarkCount,isEnd,type) values(:id,:title,:author,:image,:desc,:isPublic,:createTime,:bookfrom,:star,:starCount,:fontCount,:totalChapter,:remarkCount,:isEnd,:type)"

        cursor.execute(sql,
                       {'id': self.data['id'], 'title': self.data['bookName'], 'author': self.data['author'], 'image': image, 'desc': self.data['descript'], 'isPublic': isPublic,
                        'createTime': createTime, 'bookfrom': bookfrom, \
                        'star': star, 'starCount': self.data['totalRemarkPeople'], 'fontCount': fontCount, 'totalChapter': self.data['totalChapter'],
                        'remarkCount': self.data['totalRemarkPeople'],\
                        'isEnd': isEnd,\
                        'type':self.data['type']
                        })

        self.__connection.commit()


    # 获取ID最大值
    def getMaxId(self, dataTable):
        cursor = self.__connection.cursor()
        sql = "select max(id) from " + dataTable
        results = cursor.execute(sql)
        result = results.fetchall()
        cursor.close()
        if result[0][0] == None:
            return 0

        return result[0][0]

    # 存储书籍章节内容
    def saveChapter(self,chapter_id,book_id,chapterName,chapterContent,chapterHref):
        '''
        :param id: 章节编号
        :param book_id:书籍编号
        :param chapterName: 章节名
        :param chapterContent: 章节内容
        :return:
        '''
        id = self.getMaxId('easyRead_bookchapter') + 1

        editTime = datetime.datetime.now()
        cursor = self.__connection.cursor()

        sql = "insert OR IGNORE into easyRead_bookchapter(id,book_id,chapterName,editTime,chapterContent,chapterId,chapterHref) values(:id,:book_id,:chapterName,:editTime,:chapterContent,:chapterId,:chapterHref)"
        cursor.execute(sql, {'id': id, 'book_id': book_id, 'chapterName': chapterName, 'editTime': editTime,
                             'chapterContent': chapterContent,'chapterId':chapter_id,'chapterHref':chapterHref
                             })
        self.__connection.commit()
        print('当前存储章节：  %s' % chapterName)

    #保存评论
    def saveReamrk(self,book_id,userImage,remarkContent,userName):
        id = self.getMaxId('easyRead_bookremark') + 1
        editTime = datetime.datetime.now()
        cursor = self.__connection.cursor()

        sql = "insert OR IGNORE into easyRead_bookremark(id,book_id,userImage,remarkTime,remarkContent,userName) values(:id,:book_id,:userImage,:remarkTime,:remarkContent,:userName)"
        cursor.execute(sql, {'id': id, 'book_id': book_id, 'userImage': userImage, 'remarkTime': editTime,
                             'remarkContent': remarkContent,'userName':userName,
                             })
        self.__connection.commit()


    #下载图片
    def downloadImage(self,url,imageName):
        import requests
        try:
            response=requests.get(url)
            img=response.content
            file='./Book/Images/'+imageName+'.jpg'

            with open(file,'wb') as f:
                f.write(img)

            return True
        except Exception as e:
            print(e)
            return False
